from django.db import models

from problems.models.problem_model import ProblemModel
from users.models import User


class SubmissionModel(models.Model):
    """
        提交记录表

        用途：
        该模型用于记录用户提交代码的记录，包括提交时间、提交代码、提交结果、提交语言、提交者、题目、提交次数、提交状态、提交代码大小相关信息

        关联关系：
        - 关联用户模型 (UserModel)
        - 关联题目模型 (ProblemModel)

        创建人：
        魏文海，创建于2024年7月25日
    """
    id = models.AutoField(primary_key=True)
    language_choice = (
        (0, 'C'),
        (1, 'C++'),
        (2, 'Java'),
        (3, 'Python'),
        (4, 'Go'),
        (5, 'Rust'),
        (6, 'C#'),
        (7, 'JavaScript'),
        (8, 'PHP'),
        (9, 'Ruby'),
        (10, 'Swift'),
        (11, 'Kotlin'),
        (12, 'Dart'),
        (13, 'Objective-C'),
    )
    
    result_choice = (
        (0, '未提交'),
        (1, '等待评测'),
        (2, '评测中'),
        (3, '通过'),
        (4, '答案错误'),
        (5, '编译错误'),
        (6, '运行时错误'),
        (7, '时间超限'),
        (8, '内存超限'),
        (9, '系统错误'),
    )

    # 原有字段
    language = models.IntegerField(choices=language_choice, verbose_name='提交语言')
    update_time = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    user = models.ForeignKey(User, on_delete=models.DO_NOTHING, verbose_name='提交者')
    times = models.IntegerField(verbose_name='提交次数')
    create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    code = models.TextField(verbose_name='提交代码')
    code_size = models.IntegerField(verbose_name='提交代码大小')
    is_delete = models.BooleanField(default=False, verbose_name='是否删除')
    problem = models.ForeignKey(ProblemModel, on_delete=models.DO_NOTHING, verbose_name='题目')
    result = models.IntegerField(choices=result_choice, default=0, verbose_name='提交结果')
    remark = models.TextField(verbose_name='备注,记录错误信息等', null=True, blank=True)

    # 新增字段
    time_used = models.IntegerField(verbose_name='运行时间(ms)', null=True, blank=True)
    memory_used = models.IntegerField(verbose_name='内存占用(KB)', null=True, blank=True)
    compile_output = models.TextField(verbose_name='编译输出', null=True, blank=True)
    test_cases_passed = models.IntegerField(verbose_name='通过测试用例数', default=0)
    total_test_cases = models.IntegerField(verbose_name='总测试用例数', default=0)

    class Meta:
        db_table = 'submission'
        verbose_name = '提交记录'
        verbose_name_plural = verbose_name
        ordering = ['-create_time']  # 按创建时间倒序排序

    def __str__(self):
        return f"提交 {self.id} - 用户: {self.user.username} - 题目: {self.problem.title}"

    def get_status_display(self):
        return dict(self.result_choice)[self.result]

    def get_language_display(self):
        return dict(self.language_choice)[self.language]